import 'dart:async';

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

//一种允许用户使用给定的相机拍照的屏幕
// A screen that allows users to take a picture using a given camera.
class TakePictureScreen3 extends StatefulWidget {
  const TakePictureScreen3({
    Key? key,
    required this.camera,
  }) : super(key: key);

  final CameraDescription camera;

  @override
  TakePictureScreen3State createState() => TakePictureScreen3State();
}

class TakePictureScreen3State extends State<TakePictureScreen3> {
  late CameraController _controller;
  late Future<void> _initializeControllerFuture;
  ///声明Timer
  late Timer _timer;
  ///记录当前的时间
  int currentTimer = 9;

  @override
  void initState() {
    super.initState();
    _controller = CameraController(
      widget.camera,
      ResolutionPreset.medium,
    );
    _initializeControllerFuture = _controller.initialize();
  }

  @override
  void dispose() {
    _controller.dispose();
    _timer.cancel();
    super.dispose();
  }

  //相机倒计时
  void _cameraCountDown(){
    AudioPlayer audioPlayer = AudioPlayer();
    AudioCache audioCache=new AudioCache(prefix:'assets/audio/',fixedPlayer:audioPlayer);
    audioCache.play('daojishi.mp3');
    ///循环执行 间隔1秒
    _timer = Timer.periodic(Duration(seconds: 1), (timer) async {
      audioPlayer.pause();
      print(1);
      ///倒计时清零后拍照
      if(currentTimer==0){
        _timer.cancel();
        try {
          await _initializeControllerFuture;
          final image = await _controller.takePicture();
          await Navigator.of(context).push(
            MaterialPageRoute(
              builder: (context) => DisplayPictureScreen(
                imagePath: image.path,
              ),
            ),
          );
        } catch (e) {
          // If an error occurs, log the error to the console. 如果发生错误，将错误记录到控制台。
          print(e);
        }
        currentTimer=8;
        return;
      }
      ///自减
      currentTimer-=1;
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final deviceRatio = size.width / size.height;
    return Scaffold(
      body: FutureBuilder<void>(
        future: _initializeControllerFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            //如果Future已完成，则显示预览，拍照窗口出现
            return Container(
              color: Colors.black,
              child: Stack(children: <Widget>[
                Column(children: <Widget>[
                  Expanded(
                    flex: 3,//flex用来设置当前可用空间的占优比
                    child: Stack(
                        children: <Widget>[
                          Center(
                            child: Transform.scale(
                              scale: _controller.value.aspectRatio / deviceRatio,
                              child: AspectRatio(
                                aspectRatio: _controller.value.aspectRatio,
                                child: Center(child: CameraPreview(_controller)),
                              ),
                            ),
                          ),
                          //中间：悬浮的身份证框图
                          Positioned(
                            child: Container(
                              // color: Colors.grey,
                              alignment: Alignment.center,
                              margin: const EdgeInsets.fromLTRB(50, 50, 50, 50),
                              child:new Image.asset('assets/images/bg_zm_1.png'),
                            )
                          ),
                          //倒计时
                          if(currentTimer.toInt()!=9 && currentTimer.toInt()!=0)
                            Positioned(
                              child: Container(
                                alignment: Alignment.center,
                                child:Text("${currentTimer.toInt()}",style: TextStyle(fontSize: 100,color: Colors.white)),
                              ),
                            ),
                          //左上角返回按钮
                          Positioned(
                            top: 15,
                            left: 10,
                            child: IconButton(
                              icon: Icon(
                                Icons.chevron_left,
                                color: Colors.white,
                                size: 30,
                              ),
                              onPressed: () {
                                Navigator.pop(context);
                              },
                            ),
                          ),
                          //左下角：
                          Positioned(
                            bottom: 20.0,
                            left: 30.0,
                            child: IconButton(
                              icon: Icon(
                                Icons.announcement_outlined,
                                color: Colors.white,
                                size: 30,
                              ),
                              onPressed: () {

                              },
                            ),
                          ),
                          //中下拍照：
                          Positioned(
                            bottom: 20.0,
                            left: 160.0,
                            child: IconButton(
                              icon: Icon(
                                Icons.photo_camera,
                                color: Colors.white,
                                size: 30,
                              ),
                              onPressed: () {
                                _cameraCountDown();
                              },
                            ),
                          ),
                          //右下相册
                          Positioned(
                            bottom: 20.0,
                            right: 30.0,
                            child: IconButton(
                              icon: Icon(
                                Icons.picture_in_picture_alt_outlined,
                                color: Colors.white,
                                size: 30,
                              ),
                              onPressed: () async{
                                var pickedFile = await ImagePicker().pickImage(source: ImageSource.gallery);
                                await Navigator.of(context).push(
                                  MaterialPageRoute(
                                    builder: (context) => DisplayPictureScreen(
                                      imagePath: pickedFile!.path,
                                    ),
                                  ),
                                );
                              },
                            ),
                          ),
                        ]
                      ),
                    ),
                  ],),
                ]
              ),
            );
          } else {
            // Otherwise, display a loading indicator. 否则，显示加载中动态样式
            return const Center(child: CircularProgressIndicator());
          }
        },
      ),
    );
  }
}

// A widget that displays the picture taken by the user.显示用户所拍照片的小部件。
class DisplayPictureScreen extends StatelessWidget {
  final String imagePath;

  const DisplayPictureScreen({Key? key, required this.imagePath})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Display the Picture')),
      // The image is stored as a file on the device. Use the `Image.file`
      // constructor with the given path to display the image.
      body: Container(
        color: Colors.red,
        child: Image.file(
          File(imagePath),
        ),
      ),
    );
  }
}
